package cn.alise.qdp.service.common;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import cn.alise.consts.BaseConsts;
import cn.alise.qdp.model.user.User;

import com.alibaba.fastjson.JSONArray;


/**
 * ClassName: BaseService <br/>
 */

public class BaseService implements Serializable {
	/**	
	 * 日志对象
	 */
	protected final Logger logger = Logger.getLogger(this.getClass());
	
	/**
	 * 序列号
	 */
	private static final long serialVersionUID = -8871338859087443082L;
	
	/**
	 * 获取session对象
	 * @return
	 */
	public HttpSession getSession() {
		HttpSession session = null; 
		
		try { 
		    session = getRequest().getSession(); 
		} catch (Exception e) {
			logger.error("获取Session对象报错，原因：" + e.getMessage(), e);
		}
		
		return session; 
	} 

	/**
	 * 获取request对象
	 * @return
	 */
	public HttpServletRequest getRequest() { 
		ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); 
		return attrs.getRequest(); 
	}
	
	/**
	 * 从session中将对象清空
	 * @param key
	 */
	public void removeSessionValue(String key) {
		this.getSession().removeAttribute(key);
	}
	
	/**
	 * 从request对象中获取值
	 * @param key
	 */
	public Object getRequestValue(String key) {
		return this.getRequest().getAttribute(key);
	}
	
	/**
	 * 向session中添加值
	 * @param key
	 * @param value
	 */
	public void setSessionValue(String key, Object value) {
		this.getSession().setAttribute(key, value);
	}
	
	/**
	 * 从session对象中获取值
	 * @param key
	 * @return
	 */
	public Object getSesionValue(String key) {
		return this.getSession().getAttribute(key);
	}
	
	/**
	 * 获取异常信息
	 * @param action
	 * @param e
	 * @return
	 * @author zhuyf
	 */
	protected String getExceptionMessage(String action, Exception e) {
		Throwable source = getSqlException(e);
		return action + " -> " + e.getMessage() + (source != null ? " --> DB_ERROR:" + source.getMessage() : "");
	}
	
	/**
	 * 获取sql异常
	 * @param e
	 * @return
	 * @author zhuyf
	 */
	protected Throwable getSqlException(Exception e) {
		Throwable source = e;
		// 简单查询异常的8层Cause
		for (int i = 0; i < 8; i++) {
			if (source.getCause() == null) {
				return null;
			} else {
				source = source.getCause();
			}
			
			if (source.getClass().toString().equals(SQLException.class.toString())) {
				return source.getCause();
			}
		}
		return source;
	}
	
	
	/**
	 * 设置调用接口的参数
	 * @param params 参数名以逗号分隔
	 * @param obj 实体对象
	 * @return
	 */
	protected Map<String,String> setRequestParams(String params,Object obj) {
		Map<String, String> paramsMap = new HashMap<String, String>();
		if(obj == null) return paramsMap;
		if(StringUtils.isEmpty(params)) return paramsMap;
		String[] paramArray = params.split(",");
		for(String paramName:paramArray) {
			try {
				Field field = obj.getClass().getDeclaredField(paramName);
				field.setAccessible(true);
				Object value = field.get(obj);
				if(value == null) continue;
				paramsMap.put(paramName, value.toString());
			} catch (Exception e) {
				continue;
			}
		}
		return paramsMap;
	}
	
	/**
	 * 从session中获取账号对象
	 * @return
	 */
	public User getAccountFromSession() {
		return (User) this.getSesionValue(BaseConsts.IUser.USER_SESSION_KEY);
	}
	
	/**
	 * 将Object对象转换为指定类型的对象
	 * @param data
	 * @param clazz
	 * @return 
	 * @return 
	 * @return
	 */
	protected <T> T transfObject(Object data, Class<T> clazz) {
		return JSONArray.parseObject(data.toString(), clazz);
	}
	
	/**
	 * 将Object对象转换为指定类型的List对象
	 * @param data
	 * @param clazz
	 * @return 
	 * @return 
	 * @return
	 */
	protected <T> List<T> transfArray(Object data, Class<T> clazz) {
		return JSONArray.parseArray(data.toString(), clazz);
	}
}
